package com.fire8.dolphin.ui.plan;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.fire8.dolphin.db.PlanDAO;
import com.fire8.dolphin.model.Plan;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.wiget.BaseCalendar;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 增加康复计划
 * <功能详细描述>
 *
 * @author  wangchd
 * @version [版本号,2013-1-14]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class PlanAddActivity extends Activity
{
    private Button btnRight;
    
    private ListView lvList;
    
    //用于存放多个VIEW
    private MyAdapter lvMyAdapter;
    
    private List<Plan> planList = new ArrayList<Plan>();
    
    private ArrayList<Plan> planList2 = new ArrayList<Plan>();//需要插入数据库的
    
   
    private DolphinApplication app;
    private AlarmManager aManager;//闹钟管理器
    private PlanDAO pdDAO;
    private ProgressDialog progressDialog = null;//提示滚动条
    @Override
    protected void onStart()
    {
        super.onStart();
    }
    
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plan_add);
        app = (DolphinApplication)getApplication();
        aManager = (AlarmManager)getSystemService(Service.ALARM_SERVICE);
        btnRight = (Button)findViewById(R.id.title_bt_right);
        lvList = (ListView)findViewById(R.id.lv_plan_templete);
        lvMyAdapter = new MyAdapter(PlanAddActivity.this);
        lvList.setAdapter(lvMyAdapter);
        pdDAO = new PlanDAO(PlanAddActivity.this);
        //默认显示一项
        Plan plan = new Plan();
        plan.setTitle("");
        planList.add(plan);
        
        Button btAdd = (Button)findViewById(R.id.bt_add);
        btAdd.setOnClickListener(new OnClickListener()
        {
            
            public void onClick(View v)
            {
                Plan plan = new Plan();
                planList.add(plan);
                lvMyAdapter.notifyDataSetChanged();
            }
        });
        //头部的按钮，弹出模板供用户选择
        btnRight.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(PlanAddActivity.this,PlanTemplateActivity.class);
                startActivityForResult(intent, PlanTemplateActivity.class.hashCode());
            }
        });
        //保存按钮
        Button btEnter = (Button)findViewById(R.id.bt_next_right);
        btEnter.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                for (int i = 0; i < planList.size(); i++)
                {
                    LogUtil.d("index="+i);
                    Plan plan = planList.get(i);
                    ArrayList<Date> alarmList = plan.getAlarmList();
                    if(alarmList != null)
                    {
                        for (Date date : alarmList)
                        {
                            if(!StringUtil.isEmpty(plan.getTitle()))
                            {
                                Plan temp = new Plan();
                                temp.setDateTime(plan.getDateTime());
                                temp.setAlarmTime(DateUtil.getDayDate(date)+" "+plan.getDateTime());
                                temp.setTitle(plan.getTitle());
                                temp.setsRemoteId(0l);
                                temp.setAlarm(plan.getAlarm());
                                temp.setFinish(Plan.FINISH_NO);
                                temp.setIsPublic(1);
                                
                                String userId = app.getUserId();
                                if(!StringUtil.isEmpty(userId))
                                {
                                    temp.setUserId(Integer.valueOf(userId));
                                }
                                planList2.add(temp);
                                //创建定时器
                                
                            }
                            
                        }
                    }
                    
                }
                if(planList2.size()>0)
                {
                    LogUtil.d("要保存的计划条数："+planList2.size());
                    pdDAO.addList(planList2);
                    addAlarm(planList2);//设置提醒闹钟
                    //打开进度条窗口
                    progressDialog = ProgressDialog.show(PlanAddActivity.this, "请稍等...", "正在提交...", true);
                    new SubmitPlanTask().execute(planList2.toArray(new Plan[]{}));
                    
                }else
                {
                    Toast.makeText(PlanAddActivity.this, "您还没有输入计划内容哦", Toast.LENGTH_LONG).show();
                }
                
            }
        });
        
    }
    
    /**设置提醒闹钟**/
    private void addAlarm(List<Plan> plans)
    {
        for (Plan plan : plans)
        {
            if(plan.getAlarm() == Plan.ALARM_YES)
            {
                LogUtil.d("提醒时间："+plan.getAlarmTime());
                Date date = DateUtil.strToDate(plan.getAlarmTime(), "yyyy-MM-dd HH:mm:ss");
                Intent intent = new Intent(PlanAddActivity.this,AlarmActivity.class);
                intent.putExtra("title", plan.getTitle());
                PendingIntent pi = PendingIntent.getActivity(PlanAddActivity.this, plan.getTitle().hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
                aManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pi);
            }
        }
    }
    
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;
        
        public MyAdapter(Context context)
        {
            mInflater = LayoutInflater.from(context);
        }
        
        @Override
        public int getCount()
        {
            return planList.size();
        }
        
        @Override
        public Object getItem(int position)
        {
            return planList.get(position);
        }
        
        @Override
        public long getItemId(int position)
        {
            return 0;
        }
        
        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent)
        {
            final Plan plan = planList.get(position);
            View rowView = convertView;
            ViewHolder holder = null;
            if (rowView == null)
            {
                holder = new ViewHolder();
                rowView = mInflater.inflate(R.layout.plan_add_item, null);
                holder.txtTitle = (EditText)rowView.findViewById(R.id.txt_p2_title);
                holder.layout = (RelativeLayout)rowView.findViewById(R.id.lay_repat);
                holder.timeLayout = (RelativeLayout)rowView.findViewById(R.id.lay_time);
                holder.tvRepeatDay = (TextView)rowView.findViewById(R.id.tv_repat_day);
                holder.tvTimeDetail = (TextView)rowView.findViewById(R.id.tv_time_detail);
                holder.imgdel = (ImageView)rowView.findViewById(R.id.imgdel);
                holder.btnAlarm = (ToggleButton)rowView.findViewById(R.id.btn_alarm);
                rowView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder)rowView.getTag();
            }
            holder.txtTitle.setText(plan.getTitle());
            holder.txtTitle.setOnFocusChangeListener(new OnFocusChangeListener()
            {
                @Override
                public void onFocusChange(View v, boolean hasFocus)
                {
                    if(!hasFocus)
                    {
                        plan.setTitle(((EditText)v).getText().toString());
                    }
                }
            });
            holder.tvTimeDetail.setText(plan.getDateTime());
            final ArrayList<Date> alarmList = plan.getAlarmList();
            String alarmString="";
            if(alarmList != null)
            {
                StringBuffer sb = new StringBuffer();
                for (Date date : alarmList)
                {
                    sb.append(DateUtil.getDayDate(date));
                    sb.append(",");
                }
                alarmString = sb.substring(0, sb.length()-1);
                LogUtil.d("选中的时间"+alarmString);
            }
            holder.tvRepeatDay.setText(alarmString);
            holder.imgdel.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    planList.remove(plan);
                    lvMyAdapter.notifyDataSetChanged();
                }
            });
            holder.layout.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Intent intent = new Intent(PlanAddActivity.this,
                            BaseCalendar.class);
                    intent.putExtra("position", position);
                    if(alarmList != null)
                    {
                        intent.putExtra("alarmDateList", alarmList);
                    }
                    startActivityForResult(intent,
                            BaseCalendar.class.hashCode());
                }
            });
            holder.btnAlarm.setOnCheckedChangeListener(new OnCheckedChangeListener()
            {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    if(isChecked)
                    {
                        plan.setAlarm(Plan.ALARM_YES);
                    }else
                    {
                        plan.setAlarm(Plan.ALARM_NO);
                    }
                }
            });
            return rowView;
        }
        public final class ViewHolder
        {
            public EditText txtTitle;
            public RelativeLayout layout;
            public RelativeLayout timeLayout;
            public TextView tvRepeatDay;
            public TextView tvTimeDetail;
            public ImageView imgdel;
            public ToggleButton btnAlarm;
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(data==null)
            return;
        int position = data.getIntExtra("position", -1);
        
        if (requestCode == BaseCalendar.class.hashCode())
        {
            if (resultCode == RESULT_OK)
            {
                Plan plan = planList.get(position);
                if (null != plan)
                {
                    ArrayList<Date> dlist = (ArrayList<Date>)data.getSerializableExtra("baseClist");
                    if (dlist.size() > 0){
                        plan.setAlarmList(dlist);
                    }
                    plan.setDateTime(data.getStringExtra("hour") + ":" + data.getStringExtra("minute"));
                    lvMyAdapter.notifyDataSetChanged();
                }
            }
        }
        //从模板页面返回时
        if (requestCode == PlanTemplateActivity.class.hashCode())
        {
            if (resultCode == RESULT_OK)
            {
                List<String> lvCheckdata = data.getStringArrayListExtra("lvList");
                if (lvCheckdata == null)
                {
                    return;
                }
                for (String stitle : lvCheckdata)
                {
                    Plan plan = new Plan();
                    plan.setTitle(stitle);
                    planList.add(plan);
                }
                lvMyAdapter.notifyDataSetChanged();
            }
        }
    }
    
    private class SubmitPlanTask extends AsyncTask<Plan, Integer, String>
    {
        String msg;
        @Override
        protected String doInBackground(Plan... params)
        {
            if(!RequestUtils.getInstall().isConnect(PlanAddActivity.this))
            {
                return "网络不可用";
            }
            int len = params.length;
            for (int i = 0; i < len; i++)
            {
                Plan plan = params[i];
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("myPlan.title",plan.getTitle()));LogUtil.d("title"+plan.getTitle());
                param.add(new BasicNameValuePair("myPlan.alarmTime",plan.getAlarmTime()));
                param.add(new BasicNameValuePair("myPlan.alarm",String.valueOf(plan.getAlarm())));
                param.add(new BasicNameValuePair("myPlan.finish",String.valueOf(plan.getFinish())));
                param.add(new BasicNameValuePair("myPlan.isPublic",String.valueOf(plan.getIsPublic())));
                param.add(new BasicNameValuePair("myPlan.userId",String.valueOf(plan.getUserId())));
                String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"plan/addPlan.php", param);
                LogUtil.d("plan:"+json);
                try
                {
                    JSONObject data = new JSONObject(json);
                    String msgCode = data.getString("msgCode");
                    String desc = data.getString("desc");
                    if("1".equals(msgCode))
                    {
                        int id = data.getInt("msgBody");
                        plan.setsRemoteId(Long.valueOf(id));
                        pdDAO.update(plan);
                        
                    }else
                    {
                        msg = desc;
                    }
                }
                catch (Exception e)
                {
                    LogUtil.e("",e);
                }
                
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            //关闭提示
            progressDialog.dismiss();
            if(!StringUtil.isEmpty(result))
            {
                Toast.makeText(PlanAddActivity.this, result, Toast.LENGTH_LONG).show();
            }
            PlanAddActivity.this.finish();
        }
        
        
    }
}
